package com.xbwang.controller;

import com.xbwang.service.WeChatService;
import com.xbwang.utils.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 微信公众号controller
 * @author xbwang
 * @date 2023/9/20 14:03
 **/
@Api(tags = "微信公众号controller")
@Controller
@RequestMapping("/weChat")
public class WechatController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${wxToken}")
    private String wxToken;
    @Value("${DNS_URl}")
    private String dns_url;
    @Value("${appId}")
    private String appId;
    @Value("${appsecret}")
    private String appsecret;
    @Resource
    private WeChatService weChatService;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 微信公众号接入
     *
     * @param request
     * @param response
     */
    @ApiOperation("微信公众号接入")
    @GetMapping("/access")
    public void wxlogin(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            logger.error("获取PrintWriter异常");
        }
        if (SignUtil.checkSignature(wxToken,signature, timestamp, nonce)) {
            logger.info("微信公众号接入成功！");
            out.print(echostr);
        }
        out.close();
    }

    /**
     * 消息被动回复
     *
     * @param request
     * @param response
     */
    @ApiOperation("消息被动回复")
    @PostMapping("/access")
    public void feedbackMsg(HttpServletRequest request, HttpServletResponse response) {
        //响应消息
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("utf-8");
            out = response.getWriter();
            //被动回复消息
            String feedmsg = null;
            feedmsg = weChatService.feedbackMsg(request, response);
            logger.info("被动回复消息：{}", feedmsg);
            out.print(feedmsg);
        } catch (IOException e) {
            logger.error("获取PrintWriter异常", e);
        }
        out.close();
    }


}
